package fischl.web;

import fi.iki.elonen.NanoHTTPD;
import fischl.log.Log;
import fischl.log.LogFactory;

import java.util.ArrayList;

import java.util.List;

public class HttpServer extends NanoHTTPD {
  private static final Log log = LogFactory.get("server");
  private final List<RouteHandler> handlers = new ArrayList<>();

  public HttpServer(int port) {
    super(port);
  }

  public void addHandler(RouteHandler handler) {
    handlers.add(handler);
  }

  @Override
  public Response serve(IHTTPSession session) {
    //路由
    for (RouteHandler handler : handlers) {
      try {
        Response res = handler.handle(session);
        if (res != null) return res;
      } catch (Throwable e) {
        log.e(e);
      }
    }
    return super.serve(session);
  }

}
